package com.my.chapter18;

import java.io.*;
import java.util.*;

public class practice18 {
    static String path = ".\\src\\com\\my\\chapter18\\";
    public static void main(String[] args) throws IOException {
        String file =
                TextFile2.read(path + "practice18.java");
        TextFile2.write(path + "OutputPractice18.txt", file);
        TextFile2 text = new TextFile2(path + "OutputPractice18.txt");
        text.write(path + "OutputPractice18(2).txt");
        // Break into unique sorted list of words:
        TreeSet<String> words = new TreeSet<String>(
                new TextFile2(path + "practice18.java", "\\W+"));
        // Display the capitalized words:
        System.out.println(words.headSet("a"));
    }
}

class TextFile2 extends ArrayList<String> {
    public static String read(String fileName)
            throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader in= new BufferedReader(new FileReader(
                new File(fileName).getAbsoluteFile()));
        try {
            String s;
            while((s = in.readLine()) != null) {
                sb.append(s);
                sb.append("\n");
            }
        } finally {
            in.close();
        }
        return sb.toString();
    }

    public static void write(String fileName, String text)
            throws IOException {
        PrintWriter out = new PrintWriter(
                new BufferedWriter(new FileWriter(
                        new File(fileName).getAbsoluteFile())));
        try {
            out.print(text);
        } finally {
            out.close();
        }
    }

    public TextFile2(String fileName, String splitter)
            throws IOException {
        super(Arrays.asList(read(fileName).split(splitter)));
        if(get(0).equals("")) remove(0);
    }

    public TextFile2(String fileName) throws IOException {
        this(fileName, "\n");
    }

    public void write(String fileName) throws IOException {
        PrintWriter out = new PrintWriter(
                new BufferedWriter(new FileWriter(
                        new File(fileName).getAbsoluteFile())));
        try {
            for(String item : this)
                out.println(item);
        } finally {
            out.close();
        }
    }

}
